package com.ukao.cashregister.dialog;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.dexmaker.dx.rop.cst.CstArray;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.ClientGroupingAdapter;
import com.ukao.cashregister.base.BaseDialogFragment;
import com.ukao.cashregister.bean.ClientGroupingBean;
import com.ukao.cashregister.bean.StringBean;
import com.ukao.cashregister.bean.VipGroupBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.listener.OnItemChildClickListener;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.Utils;
import com.ukao.cashregister.widget.StateImageView;
import com.ukao.cashregister.widget.TwinklingLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 客户分组对话框
 */
public class ClientGroupingDialogFragment extends BaseDialogFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private  Unbinder unbinder;
    @BindView(R.id.shut_btn)
    StateImageView shutBtn; //关闭
    @BindView(R.id.grouping_twinkling_layout)
    TwinklingLayout mGroupingTwinklingLayout;
    @BindView(R.id.grouping_list_recycler)
    RecyclerView mGroupingListRecycler;
    @BindView(R.id.btn_cancel)
    Button  cancelBtn;
    @BindView(R.id.btn_confirm)
    Button confirmBtn;
    @BindView(R.id.tv_checked_name)
    TextView tvCheckedName;   //选中的名字
    private String userId;  //用户ID
    private  ClientGroupingAdapter groupingAdapter;
    private  boolean isFirstRefresh=true;
    private  int  pageNum;  //页数
    private final   static int  pageSize=50;  //一页的数量
    private   ClientGroupingBean  selectedGrouping;  //选中的分组类

    private OnDialogSureClickListener mDialogConfirmClickListener;
    public  void  setOnDialogSureClickListener(OnDialogSureClickListener mOnItemChildClickListener){
        this.mDialogConfirmClickListener=mOnItemChildClickListener;
    }
    public ClientGroupingDialogFragment() {
    }

    // TODO: Rename and change types and number of parameters
    public static ClientGroupingDialogFragment newInstance(ClientGroupingBean clientGroupingBean, String userId) {
        ClientGroupingDialogFragment fragment = new ClientGroupingDialogFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, clientGroupingBean);
        args.putString(ARG_PARAM2, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            selectedGrouping = getArguments().getParcelable(ARG_PARAM1);
            userId = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_client_grouping_dialog, container, false);
        unbinder=ButterKnife.bind(this,view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getDialog().setCanceledOnTouchOutside(false);  //点击外面不取消
        initViews();
    }

    private void   initViews(){
        tvCheckedName.setText(selectedGrouping.getName());//设置选中的分组名
        mGroupingListRecycler.setLayoutManager(new GridLayoutManager(getActivity(),7));
        List<ClientGroupingBean>    GroupingList=new ArrayList<>();
        groupingAdapter=new ClientGroupingAdapter(getActivity(),GroupingList);
        groupingAdapter.setOnItemClickListener(mOnItemClickListener);
        mGroupingListRecycler.setAdapter(groupingAdapter);
        mGroupingTwinklingLayout.setOnRefreshListener(mRefreshListenerAdapter);
    }

    /**
     * 刷新和加载更多
     */
    private RefreshListenerAdapter mRefreshListenerAdapter = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);
            pageNum=0;
            groupingAdapter.getDatas().clear();  //清空集合数据
            if(selectedGrouping.getId()!=-1){  //添加默认分组字段
                ClientGroupingBean  groupingBean=new ClientGroupingBean();
                groupingBean.setId(-1);
                groupingBean.setName("默认分组");
                groupingAdapter.getDatas().add(0,groupingBean);
            }else {  //等于-1 就不用重新new默认分组
                groupingAdapter.getDatas().add(selectedGrouping);
            }
            requestGroupingData();
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            super.onLoadMore(refreshLayout);
            requestGroupingData();
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if(isFirstRefresh){
            //自动刷新H
            mGroupingTwinklingLayout.startRefresh();
            isFirstRefresh=false;
        }
    }

    OnItemClickListener mOnItemClickListener=new MyOnItemClickListener(){
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            List<ClientGroupingBean>  list =groupingAdapter.getDatas();
            ClientGroupingBean mItemGroup  =list.get(i);
            if(!mItemGroup.isSelected()){  //没有选中的话 就设置选中
                for (int j = 0; j < list.size(); j++) {
                    if (i != j) {
                        list.get(j).setSelected(false);
                    }else {
                        list.get(i).setSelected(true);
                    }
                }
                tvCheckedName.setText(mItemGroup.getName());
                selectedGrouping=mItemGroup;
                groupingAdapter.notifyDataSetChanged();
            }
        }
    };
    /**
     * 请求分组数据
     */
    private void  requestGroupingData(){
        HashMap mHashMap=new HashMap<String,String>();
        pageNum++;
        mHashMap.put("pageNum",String.valueOf(pageNum));
        mHashMap.put("pageSize",String.valueOf(pageSize));
        mHashMap.put("accessToken", SaveParamets.getToken(Utils.getContext()));
        addSubscription(apiStores().clientGroupingData(Constant.createParameter(mHashMap)),
                new ApiCallback<ClientGroupingBean>() {
                    @Override
                    public void onSuccess(ClientGroupingBean model) {
                        groupingAdapter.getDatas().addAll(model.getData());
                        setCheckedGrouping();
                        if(model.getData().size()<pageSize){
                                mGroupingTwinklingLayout.setEnableLoadmore(false);  //静止上拉加载
                                mGroupingTwinklingLayout.setEnableOverScroll(false);
                        }
                        groupingAdapter.notifyDataSetChanged();
                    }
                    @Override
                    public void onFinish() {
                        //结束刷新
                        mGroupingTwinklingLayout.finishRefreshing();
                        //结束加载更多
                        mGroupingTwinklingLayout.finishLoadmore();
                    }

        });
    }

    /**
     * 保存客户分组数据
     */
    private void  saveGroupingData(){
        super.showProgressDialog();
        HashMap mHashMap=new HashMap<String,String>();
        mHashMap.put("userId",userId);
        mHashMap.put("groupId",String.valueOf(selectedGrouping.getId()));
        mHashMap.put("accessToken", SaveParamets.getToken(Utils.getContext()));
        addSubscription(apiStores().clientGroupingDataSave(Constant.createParameter(mHashMap)),
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {
                            if(model.getHttpCode()==200){
                                mDialogConfirmClickListener.onSureItemClick(selectedGrouping);
                            }else {
                                T.show(model.getMsg());
                            }
                    }
                    @Override
                    public void onFinish() {
                        ClientGroupingDialogFragment.this.dismissProgressDialog();
                        dismiss();
                    }

                });
    }

    /**
     * 设置选中的分组
     */
  private void  setCheckedGrouping(){
      for (ClientGroupingBean groupingBean : groupingAdapter.getDatas()) {
                    if(selectedGrouping.getId()==groupingBean.getId()){
                        groupingBean.setSelected(true);
                        break;
                    }
      }
  }


    @OnClick({R.id.shut_btn, R.id.btn_confirm,R.id.btn_cancel})
    public void onViewClicked(View view) {
          switch (view.getId()){
              case R.id.shut_btn:
                  dismiss();
                  break;
              case R.id.btn_cancel:
                  dismiss();
                  break;
              case R.id.btn_confirm:
                  saveGroupingData();
                  break;
          }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();//解绑
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
